package com.winit.common.base;

import com.alibaba.fastjson.JSONObject;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.HashMap;
import java.util.Map;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

/**
 * Created by keel2008 on 16/1/15.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"/applicationContext.xml", "file:src/main/webapp/WEB-INF/springmvc-servlet.xml"})
public abstract class BaseWebTestCase {

    @Autowired
    protected WebApplicationContext wac;

    protected MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    public String doLogin()throws Exception{
        final Map<String,String> resultMap = new HashMap<String,String>();

        this.mockMvc.perform(get("/user/login").accept(MediaType.parseMediaType("application/json;charset=UTF-8")).
                param("userName", "admin").
                param("passWord", "admin"))
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code").value("0"))
                .andExpect(jsonPath("$.userInfo.userName").value("admin"))
                .andExpect(jsonPath("$.userInfo.userRole").value("admin")).andDo(new ResultHandler() {
            public void handle(MvcResult result) throws Exception {
                JSONObject jo =  JSONObject.parseObject(result.getResponse().getContentAsString());
                resultMap.put("tokenId",jo.getJSONObject("data").getString("tokenId"));
            }
        });

        return resultMap.get("tokenId");
    }
}
